<template>
	<view id="wrapper">
		<!-- 地图底框 -->
		<div v-if="showGaoDeMap === true" id="container"></div>
		<u-tag :text="'当前速度:' + this.speed + 'm/s'"type="success" class="speedTag"></u-tag>
		<view :prop="endLocation" :change:prop="test.onEndLocationChange"></view>
		<view :prop="nowLocation" :change:prop="test.onNowLocationChange"></view>
		<iframe src="http://yiyuy.nat300.top/getCameraHTML" class="camera"></iframe>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 开始跑步时的起点坐标和终点坐标
				startLocation: [],
				endLocation: [],
				// 存储每次获取当前位置
				nowLocation: [],
				requestUrl: '',
				// 用于控制是否显示地图组件
				showGaoDeMap: false,
				costTime: 0,
				// 速度 单位 米/秒
				speed: 0,
			};
		},
		created() {
			// 拿到传递过来的数据
			let data = uni.getStorageSync('data');
			this.endLocation = data.endLocation
			this.nowLocation = data.startLocation
			if (this.endLocation !== undefined && this.endLocation.length > 0) {
				this.showGaoDeMap = true;
				let that = this;
				setInterval(function() {
					that.getLocation();
					that.costTime += 7
					let distance = that.getDistance(this.nowLocation[0],this.nowLocation[1],this.endLocation[0],this.endLocation[1])
					that.speed = distance / that.costTime
				}, 7000)
			}
		},
		methods: {
			// 计算两点之间直线距离
			getDistance(lat1, lon1, lat2, lon2) {
				var radLat1 = (lat1 * Math.PI) / 180; //将角度换算为弧度
				var radLat2 = (lat2 * Math.PI) / 180; //将角度换算为弧度
				var a = radLat1 - radLat2;
				var b = (lon1 * Math.PI) / 180 - (lon2 * Math.PI) / 180;
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math
					.pow(
						Math.sin(b / 2), 2)));
				s = s * 6378137.0; // 取WGS84标准参考椭球中的地球长半径(单位:m)
				//s = Math.round(s * 10000) / 10000; //两点之间距离(保留四位)
				return s; //(单位:m)
			},
			//获取经纬度
			getLocation() {
				uni.getLocation({
					type: 'gcj02', //返回可以用于uni.openLocation的经纬度
					success: (res) => {
						let locationArr = []
						locationArr[0] = res.longitude
						locationArr[1] = res.latitude
						this.nowLocation = locationArr
					}
				});
			},
		},
	}
</script>

<script module="test" lang="renderjs">
	import AMapLoader from "@amap/amap-jsapi-loader";

	export default {
		name: "run",
		data() {
			return {
				map: '',
				marker: null,
				// 第一个数组 代表路径规划出来的路径结果 用来绘制底图
				originalPath: [],
				// 第二个数组 代表走的路径的历史记录 用来绘制运动路径
				movedHistoryPath: [],
				// 第三个数组 用来做到从一个点移动到另一个点的数组 为了做到这个效果 这个数组大小固定为2 代表从起点[0]走到终点[1]
				movePath: [],
				// 总路径多少
				distance: 0,
				// 耗费时间
				time: 0,
				// 判断是直接打开的本页面还是跳转的 只有跳转的才能显示高德地图
				showGaoDeMap: false,
				// service层中的变量 代表从上一个页面跳转过来时起始坐标 终点坐标
				startLocation: [],
				endLocation: []
			}
		},
		mounted() {
			if (this.showGaoDeMap === true) {
				console.log('初始化地图')
				this.initMiniMap()
			}
		},
		unmounted() {
			this.map?.destroy();
		},
		methods: {
			onEndLocationChange(newValue, oldValue, ownerInstance, instance) {
				if (newValue !== undefined && newValue.length > 0) {
					this.endLocation = newValue;
					this.showGaoDeMap = true;
				}
			},
			onNowLocationChange(newValue, oldValue, ownerInstance, instance) {
				// 移动
				if (newValue !== undefined && newValue.length > 0) {
					this.startLocation = newValue;
					this.originalPath.push(newValue)
					this.movedHistoryPath.push(oldValue)
					this.movePath.push(newValue)

					let len = this.movePath.length;
					let last = this.movePath[len - 1];
					if (len >= 2) {
						this.movePath = []
						this.movePath.push(last);
					}
					this.movePath.push(newValue)
					this.movedHistoryPath.push(newValue)
					if (this.marker !== null) {
						this.marker.moveAlong(this.movePath, {
							duration: 1000,
							autoRotation: true
						})
					}
				}
			},
			initMiniMap() {
				window._AMapSecurityConfig = {
					securityJsCode: "94697b54d35ad233d46a0364900a86c9",
				};
				AMapLoader.load({
						key: "bd1509b2c8644f4eb8ac504fbf4db856", // 申请好的Web端开发者Key，首次调用 load 时必填
						version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
						plugins: ["AMap.Scale",
							"AMap.PlaceSearch",
							"AMap.AutoComplete",
							"AMap.Walking",
							"AMap.MoveAnimation"
						], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
					})
					.then((AMap) => {
						// 初始化地图
						let that = this;
						this.map = new AMap.Map("container", {
							// 设置地图容器id
							viewMode: "3D", // 是否为3D地图模式
							// center: [116.397428, 39.90923], // 初始化地图中心点位置
							center: this.startLocation,
							zoom: 17, // 初始化地图级别
							resizeEnable: true,
						});

						// 步行导航配置
						var walkOption = {
							map: that.map,
							panel: "panel"
						}
						var walking = new AMap.Walking(walkOption)
						//根据起终点坐标规划步行路线
						walking.search(this.startLocation, this.endLocation, function(status, result) {
							// result即是对应的不行路线数据信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_RidingResult
							if (status === 'complete') {
								console.log('路径规划成功')
								// 查询成功后 构造originalPath数组
								var routes = result.routes[0]
								that.distance = routes.distance
								that.time = routes.time
								var steps = routes.steps
								for (let i = 0; i < steps.length; i++) {
									that.originalPath.push(steps[i]["end_location"])
								}

								// 当路线规划完毕后 绘制路线
								that.marker = new AMap.Marker({
									map: that.map,
									position: that.startLocation,
									icon: 'https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png',
									offset: new AMap.Pixel(-25, 0),
								});
								// 绘制轨迹
								var polyline = new AMap.Polyline({
									map: that.map,
									path: that.originalPath,
									showDir: true,
									strokeColor: '#28F', //线颜色
									strokeOpacity: 1, //线透明度
									strokeWeight: 6, //线宽
									strokeStyle: "solid" //线样式
								})

								//移动后的轨迹
								var passedPolyline = new AMap.Polyline({
									map: that.map,
									strokeColor: '#FF0000', //线颜色
									strokeWeight: 6, //线宽
									strokeOpacity: 0.5,
								})

								that.marker.on('moving', function(e) {
									console.log('!!')
									passedPolyline.setPath(that.movedHistoryPath)
									that.map.setCenter(e.target.getPosition(), true)
								})
							} else {
								console.log('步行路线数据查询失败' + result)
							}
						});

						// this.map.setFitView()
					})
					.catch((e) => {
						console.log(e);
					});
			}
		}
	}
</script>

<style>
	#wrapper {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	#container {
		z-index: 99;
		width: 100%;
		height: 20%;
		box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
	}
	
	.camera {
		width: 100%;
		flex: 1
	}
	
	.speedTag {
		position: absolute;
		z-index: 100;
	}
</style>